package com.hmdp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        String shopTypeKey = CACHE_SHOP_TYPE_KEY;
        // 1. 从Redis查询商户类型缓存
        String shopTypeJson = stringRedisTemplate.opsForValue().get(shopTypeKey);
        // 2. 判断缓存是否命中
        if(StringUtils.isNotBlank(shopTypeJson)){
            // 3. 命中, 返回商户类型
            List<ShopType> shopTypes = JSON.parseArray(shopTypeJson, ShopType.class);
            return Result.ok(shopTypes);
        }
        // 4. 未命中, 从数据库查询商户类型
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        // 5. 将商户类型数据写入Redis并返回
        stringRedisTemplate.opsForValue().set(shopTypeKey, JSON.toJSONString(shopTypes));
        stringRedisTemplate.expire(shopTypeKey, CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
        return Result.ok(shopTypes);
    }
}
